package com.cloudea.lotus.lambda;

import com.cloudea.lotus.Request;
import com.cloudea.lotus.Response;
import com.cloudea.lotus.bo.UserInfo;
import com.cloudea.lotus.common.TokenManager;
import com.cloudea.lotus.utils.JWTUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * 此类用于权限的鉴定，采用装饰器模式
 */
public class LotusLambdaFilter extends LotusLambda {
    private Logger logger = Logger.getLogger(this.getClass());
    private LotusLambdaImpl lotusLambda;
    private TokenManager tokenManager;

    public LotusLambdaFilter(LotusLambdaImpl lotusLambda, TokenManager tokenManager){
        this.lotusLambda = lotusLambda;
        this.tokenManager = tokenManager;
    }

    @Override
    public Response get(Request request) {
        //从request中取出token
        String token = request.getParameters().remove("token");
        if(token == null){
            return Response.fail("请输入token");
        }

        //解析token
        UserInfo userInfo = null;
        try {
            userInfo = JWTUtil.restore(token, tokenManager.getTokens());
        } catch (Exception e) {
            return Response.fail(String.valueOf(e.getMessage()));
        }

        // 代理
        Response response = lotusLambda.get(request);
        if(response.getCode() != 0){
            return response;
        }

        // 判断是单个对象还是数组
        Object data = response.getData();
        JsonArray array = null;
        if(data.getClass() == JsonArray.class){
            array = (JsonArray) data;
        }else{
            return Response.success(data);
        }

        // 判读是否存在不能访问的记录
        String objectName = lotusLambda.getObjectName();
        for(int i = 0; i < array.size(); i++){
            JsonObject object = array.get(i).getAsJsonObject();
            String readCreateId = object.get("create_id").getAsString();
            String readObjectRole = object.get("object_role").getAsString();
            if(! userInfo.getPerms().contains(objectName + "_selectAll")){
                if(! (userInfo.getPerms().contains(objectName + "_selectGroup") && userInfo.getRoles().contains(readObjectRole))){
                    if(! (userInfo.getPerms().contains(objectName + "_select") && userInfo.getUserId().equals(readCreateId))){
                        return Response.fail("存在没有权限访问的记录, 查询终止");
                    }
                }
            }
        }

        return response;
    }

    @Override
    public Response post(Request request) {
        //从request中取出token
        String token = request.getParameters().remove("token");
        if(token == null){
            return Response.fail("请输入token");
        }

        //解析token
        UserInfo userInfo = null;
        try {
            userInfo = JWTUtil.restore(token, tokenManager.getTokens());
        } catch (Exception e) {
            return Response.fail(String.valueOf(e.getMessage()));
        }

        // 判断有无insert权限
        // logger.debug("当前权限:" + userInfo.getPerms());
        if(userInfo.getPerms().contains(lotusLambda.getObjectName() + "_insert")){
            if(request.getParameter("create_id") == null){
                request.setParameter("create_id", userInfo.getUserId());
            }
            if(request.getParameter("update_id") == null){
                request.setParameter("update_id", userInfo.getUserId());
            }

            if(request.getParameter("object_role") == null){
                request.setParameter("object_role", "0");
            }
            return lotusLambda.post(request);
        }

        return Response.fail("没有权限");
    }

    @Override
    public Response put(Request request) {
        //从request中取出token
        String token = request.getParameters().remove("token");
        if(token == null){
            return Response.fail("请输入token");
        }

        //解析token
        UserInfo userInfo = null;
        try {
            userInfo = JWTUtil.restore(token, tokenManager.getTokens());
        } catch (Exception e) {
            return Response.fail(String.valueOf(e.getMessage()));
        }

        if(request.getId().equals("")){
            return Response.fail("请输入id");
        }

        //判断是否更新元信息
        String id = request.getParameter("id");
        String createId = request.getParameter("create_id");
        String updateId = request.getParameter("update_id");
        String objectRole = request.getParameter("object_role");
        List<String> perms = userInfo.getPerms();
        List<String> roles = userInfo.getRoles();
        Response response = lotusLambda.get(request);
        if(response.getCode() != 0){
            return response;
        }
        String objectName = lotusLambda.getObjectName();
        JsonObject object = (JsonObject) response.getData();
        String realCreateId =  object.getAsJsonPrimitive("create_id").getAsString();
        String realObjectRole = object.getAsJsonPrimitive("object_role").getAsString();

        //如遇更新元信息
        if(id != null || createId != null || updateId != null || objectRole != null){
            // 判断有无Admin类的权限
            if(!perms.contains(objectName + "_adminAll")){
                if(!(perms.contains(objectName + "_admin") && userInfo.getUserId().equals(realCreateId))){
                    if(!(perms.contains(objectName + "_adminGroup") && roles.contains(realObjectRole))){
                        return Response.fail("没有与admin有关的权限");
                    }
                }
            }
        }else{
            // 判断有无更新的权限
            if(!perms.contains(objectName + "_updateAll")){
                if(!(perms.contains(objectName + "_update") && userInfo.getUserId().equals(realCreateId))){
                    if(!(perms.contains(objectName + "_updateGroup") && roles.contains(realObjectRole))){
                        return Response.fail("没有权限");
                    }
                }
            }
        }
        //更新信息
        if(updateId == null){
            request.setParameter("update_id", userInfo.getUserId());
        }
        return lotusLambda.put(request);
    }

    @Override
    public Response delete(Request request) {
        //从request中取出token
        String token = request.getParameters().remove("token");
        if(token == null){
            return Response.fail("请输入token");
        }

        //解析token
        UserInfo userInfo = null;
        try {
            userInfo = JWTUtil.restore(token, tokenManager.getTokens());
        } catch (Exception e) {
            return Response.fail(String.valueOf(e.getMessage()));
        }

        if(request.getId().equals("")){
            return Response.fail("请输入id");
        }

        //获取基本信息
        List<String> perms = userInfo.getPerms();
        List<String> roles = userInfo.getRoles();
        Response response = lotusLambda.get(request);
        if(response.getCode() != 0){
            return response;
        }
        String objectName = lotusLambda.getObjectName();
        JsonObject object = (JsonObject) response.getData();
        String realCreateId =  object.getAsJsonPrimitive("create_id").getAsString();
        String realObjectRole = object.getAsJsonPrimitive("object_role").getAsString();

        // 判断有无删除的权限
        if(!perms.contains(objectName + "_deleteAll")){
            if(!(perms.contains(objectName + "_delete") && userInfo.getUserId().equals(realCreateId))){
                if(!(perms.contains(objectName + "_deleteGroup") && roles.contains(realObjectRole))){
                    return Response.fail("没有权限");
                }
            }
        }
        return lotusLambda.delete(request);
    }
}
